package com.penghaisoft.microwms.product.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.dto.ProCountingDto;
import com.penghaisoft.microwms.common.dto.ProStorageDto;
import com.penghaisoft.microwms.common.dto.RawStorageDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.ProContractChange;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.common.wms.model.RawContractChange;
import com.penghaisoft.microwms.common.wms.model.RawLockLog;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.product.dao.ProStorageSnMapper;
import com.penghaisoft.microwms.product.dao.ProContractChangeMapper;
import com.penghaisoft.microwms.product.service.IProStorageSnService;

/**
 * @Description 成品库存明细表 service
 * @author luoteng
 * @date 2018年6月6日 下午2:50:00 
 * @version 1.0
 */
@Service("proStorageSnService")
public class ProStorageSnServiceImpl extends BaseService implements IProStorageSnService{
		@Resource
		private ProStorageSnMapper proStorageSnMapper;
		@Resource
		private ProContractChangeMapper proContractChangeMapper;
		
		
		
		

		
	  /**
	   * 新增记录
	   * @param baseResource
	   * @return
	   */
		@Override
		public Resp create(ProStorageSn proStorageSn){
			proStorageSnMapper.create(proStorageSn);
			return success();
		}

	  /**
	   * 删除记录（逻辑删除）
	   * @param baseResource
	   * @return
	   */
		@Override
		public Resp delete(ProStorageSn proStorageSn){
			proStorageSnMapper.delete(proStorageSn);
			return success();
		}
		
	  /**
	   * 查询列表
	   * @param pager
	   * @param baseResource
	   * @return
	   */
		@Override
		public Pager<ProStorageSn> findListByCondition(int page, int rows,ProStorageSn condition){
		    Pager<ProStorageSn> pager = new Pager<>();
		    pager.setPage(page);
		    pager.setRows(rows);
    		condition.preQuery();
    		long size = proStorageSnMapper.queryCount(condition);
    		List<ProStorageSn> records = new ArrayList<ProStorageSn>();
    		if(size > 0){
    			records = proStorageSnMapper.queryList(pager,condition);
    		}
			pager.setRecords(records);
			pager.setTotalCount(size);
			return pager;
		}

	  /**
	   * 查询单条
	   * @param id
	   * @return
	   */
		@Override
		public ProStorageSn findById(String id){
			return proStorageSnMapper.queryById(id);
		}
		
	  /**
	   * 修改记录
	   * @param baseResource
	   * @return
	   */
		@Override
		public Resp update(ProStorageSn proStorageSn){
			Resp resp = new Resp();
			resp.setCode(Constant.SUCCESS);
			//查出信息
			ProStorageSn tmp = new ProStorageSn();
			tmp.setStorageSnId(proStorageSn.getStorageSnId());
			List<ProStorageSn> list = proStorageSnMapper.queryByAny(tmp);
			if(list.size() <= 0){
				resp.setCode(Constant.FAIL);
				resp.setMsg("查询不到条码");
				return resp;
			}
			proStorageSnMapper.updateContractNoBySelect(proStorageSn);
			//记录合同号修改日志
			if(list.size()>0){
				ProContractChange procontractChange = new ProContractChange();
				procontractChange.setBarcode(list.get(0).getBarcode());
				procontractChange.setAmount(list.get(0).getAmount());
				procontractChange.setUnit(list.get(0).getUnit());
				procontractChange.setContractNoOld(list.get(0).getContractNo());
				procontractChange.setContractNoNew(proStorageSn.getContractNo());
				procontractChange.setModel(list.get(0).getModel());
				procontractChange.setModelDesc(list.get(0).getModelDesc());
				procontractChange.setModelType(list.get(0).getModelType());
				procontractChange.setWlCode(list.get(0).getWlCode());
				procontractChange.setCreateBy(proStorageSn.getLastModifiedBy());
				procontractChange.setGmtCreate(proStorageSn.getGmtModified());
				procontractChange.setActiveFlag("1");
				proContractChangeMapper.create(procontractChange);
			}
			
			return resp;
		}
		
		@Override
		public Pager<ProStorageDto> findStorageListByCondition(int page, int rows,ProStorageDto condition){
		    Pager<ProStorageDto> pager = new Pager<>();
		    pager.setPage(page);
		    pager.setRows(rows);
    		long size = proStorageSnMapper.queryStorageListCount(condition);
    		List<ProStorageDto> records = new ArrayList<ProStorageDto>();
    		if(size > 0){
    			records = proStorageSnMapper.queryStorageList(pager,condition);
    		}
			pager.setRecords(records);
			pager.setTotalCount(size);
			return pager;
		}

		@Override
		public List<ProStorageSn> queryByAny(ProStorageSn proStorageSn) {
			
			return proStorageSnMapper.queryByAny(proStorageSn);
		}

		@Override
		public List<ProStorageSn> queryLose(ProCountingDto proCountingDto) {
			
			return proStorageSnMapper.queryLose(proCountingDto);
		}
		
		@Override
		public List<ProStorageSn> findProStorageSnByCondition(ProStorageSn proStorageSn) {

			return proStorageSnMapper.queryProStorageSnByCondition(proStorageSn);
		}
		/**
		 * @Title: updateProStorageSnStatus
		 * @Description: 冻结解冻条码
		 * @date 2018年5月22日 上午11:24:53
		 */
		@Override
		@Transactional
		public Resp updateProStorageSnStatus(List<ProStorageSn> list,
				RawLockLog rawLockLog) {
			ProStorageSn proStorageSn = new ProStorageSn();
			List<Integer> proStorageSnIdList = new ArrayList<Integer>();
			String currentUserName = rawLockLog.getLockBy();
			Date date = new Date();
			for (ProStorageSn tmp : list) {
				proStorageSnIdList.add(tmp.getStorageSnId());

//				ProStorageSn cond = new ProStorageSn();
//				cond.setStorageSnId(tmp.getStorageSnId());
//				// 根据snid（唯一）查询，实际一条sn数据
//				List<ProStorageSn> proStorageSnlist = proStorageSnMapper.queryProStorageSnByCondition(cond);
//				if (proStorageSnlist.size() > 0) {
//					// 冻结解冻日志记录
//					RawLockLog lockLog = new RawLockLog();
//					lockLog.setBarcode(proStorageSnlist.get(0).getBarcode());
//					lockLog.setModel(proStorageSnlist.get(0).getModel());
//					lockLog.setModelDesc(proStorageSnlist.get(0).getModelDesc());
//					lockLog.setWlCode(proStorageSnlist.get(0).getWlCode());
//					lockLog.setLockReason(tmp.getLockReason());
//					lockLog.setLockBy(currentUserName);
//					lockLog.setLockDate(date);
//					lockLog.setLockType(tmp.getBarcodeStatus());
//					lockLog.setGmtCreate(date);
//					lockLog.setCreateBy(currentUserName);
//					lockLog.setActiveFlag("1");
//					rawLockLogMapper.create(lockLog);
//				}

			}
			// rawStorageSnIdList条码集合（一次更新）
			proStorageSn.setProStorageSnIdList(proStorageSnIdList);
			proStorageSn.setLockReason(list.get(0).getLockReason());
			proStorageSn.setLastModifiedBy(currentUserName);
			proStorageSn.setGmtModified(date);
			String status = list.get(0).getBarcodeStatus();
			proStorageSn.setBarcodeStatus(status);
			// 冻结解冻更新状态
			Integer updateCnt = proStorageSnMapper.updateOpenClose(proStorageSn);
			System.out.println("更改数量：" + updateCnt);
			if (updateCnt.intValue() <= 0) {
				throw new RuntimeException("更改条码失败");
			}
			int modiNum = proStorageSn.getProStorageSnIdList().size();
			if (updateCnt.intValue() != modiNum) {
				throw new RuntimeException("更新条码的数量和修改条码的数量不一致！");
			}
			return success();
		}

		@Override
		public Resp updateProStorageSnWl(ProStorageSn proStorageSn) {
			Integer updateCnt = proStorageSnMapper.updateWlByCode(proStorageSn);
			if(updateCnt.intValue() == 1){
				return success();
			}else{
				return fail("更改状态失败");
			}
		}

		@Override
		public Resp updateProStorageSn(ProStorageSn proStorageSn) {
			Integer updateCnt = proStorageSnMapper.updateBySelect(proStorageSn);
			if(updateCnt.intValue() == 1){
				return success();
			}else{
				return fail("更改状态失败");
			}
		}

		/* @Title: findProStorageSnCharge 
		 * @Description: 记账in
		 * @author jzh
		 * @date 2018年7月30日 下午2:21:41 
		 */
		@Override
		public Pager<ProStorageSn> findProStorageSnCharge(int page, int rows, ProStorageSn proStorageSn) {
			Pager<ProStorageSn> pager = new Pager<>();
			pager.setPage(page);
			pager.setRows(rows);
			proStorageSn.preQuery();
			
			List<String> modelTypeList = new ArrayList<String>();
			modelTypeList.add(Constant.MODEL_RRT);
			modelTypeList.add(Constant.MODEL_DUT);
			proStorageSn.setModelTypeList(modelTypeList);
			
			long size = proStorageSnMapper.queryCountChargeIn(proStorageSn);
			List<ProStorageSn> records = new ArrayList<ProStorageSn>();
			if (size > 0) {
				records = proStorageSnMapper.queryListChargeIn(pager, proStorageSn);
			}
			pager.setRecords(records);
			pager.setTotalCount(size);
			return pager;
		}

		/* @Title: findChargeOut 
		 * @Description: 记账出库
		 * @author jzh
		 * @date 2018年7月31日 下午4:22:58 
		 */
		@Override
		public Pager<ProStorageSn> findChargeOut(int page, int rows, ProStorageSn proStorageSn) {
			Pager<ProStorageSn> pager = new Pager<>();
			pager.setPage(page);
			pager.setRows(rows);
			proStorageSn.preQuery();
			
			List<String> modelTypeList = new ArrayList<String>();
			modelTypeList.add(Constant.MODEL_RRT);
			modelTypeList.add(Constant.MODEL_DUT);
			proStorageSn.setModelTypeList(modelTypeList);
			
			long size = proStorageSnMapper.queryCountChargeOut(proStorageSn);
			List<ProStorageSn> records = new ArrayList<ProStorageSn>();
			if (size > 0) {
				records = proStorageSnMapper.queryListChargeOut(pager, proStorageSn);
			}
			pager.setRecords(records);
			pager.setTotalCount(size);
			return pager;
		}

		/* @Title: createChargeOut 
		 * @Description: 记账出库新增
		 * @author jzh
		 * @date 2018年8月1日 下午3:09:54 
		 */
		@Override
		public Resp createChargeOut(ProStorageSn proStorageSn) {
			Resp resp = new Resp();
			
			ProStorageDto proStorageDto = new ProStorageDto();
			proStorageDto.setModel(proStorageSn.getModel());
			proStorageDto.setModelType(proStorageSn.getModelType());
			List<ProStorageDto> records = proStorageSnMapper.queryStorageList(null, proStorageDto);
			if(records == null || records.isEmpty()){
				resp.setCode(Constant.FAIL);
				resp.setMsg("该原材料型号没有库存！");
				return resp;
			}else{
				ProStorageDto compare = records.get(0);
				if(proStorageSn.getAmount().negate().compareTo(compare.getAvailAmount()) > 0){
					resp.setCode(Constant.FAIL);
					resp.setMsg("该原材料型号库存不足！");
					return resp;
				}
				proStorageSnMapper.create(proStorageSn);
			}
			return success();
		}

		/* @Title: updateChargeOut 
		 * @Description: 记账出库修改
		 * @author jzh
		 * @date 2018年8月1日 下午3:10:10 
		 */
		@Override
		public Resp updateChargeOut(ProStorageSn proStorageSn) {
			Resp resp = new Resp();
			
			ProStorageSn tmp = proStorageSnMapper.queryById(proStorageSn.getStorageSnId().toString());
			
			ProStorageDto rawStorageDto = new ProStorageDto();
			rawStorageDto.setModel(proStorageSn.getModel());
			rawStorageDto.setModelType(proStorageSn.getModelType());
			List<ProStorageDto> records = proStorageSnMapper.queryStorageList(null, rawStorageDto);
			if(records == null || records.isEmpty()){
				resp.setCode(Constant.FAIL);
				resp.setMsg("该原材料型号没有库存！");
				return resp;
			}else{
				ProStorageDto compare = records.get(0);
				BigDecimal nowAddAmount = proStorageSn.getAmount().negate().subtract(tmp.getAmount().negate());
				if(nowAddAmount.compareTo(BigDecimal.ZERO) > 0){
					if(nowAddAmount.compareTo(compare.getAvailAmount()) > 0){
						resp.setCode(Constant.FAIL);
						resp.setMsg("该原材料型号库存不足！");
						return resp;
					}
				}
				
				proStorageSnMapper.updateBySelect(proStorageSn);
			}
			return success();
		}

		/* @Title: batchUpdateProContact 
		 * @Description: 批量修改成品合同号
		 * @author jzh
		 * @date 2018年8月23日 上午10:15:48 
		 */
		@Override
		@Transactional
		public Resp batchUpdateProContact(ProStorageSn proStorageSn) {
			Resp resp = new Resp();
			resp.setCode(Constant.SUCCESS);
			ProStorageSn tmp = new ProStorageSn();
			tmp.setContractNo(proStorageSn.getContractNoOld());
			tmp.setModel(proStorageSn.getModel());
			tmp.setModelType(proStorageSn.getModelType());
			tmp.setWlCode(proStorageSn.getWlCode());
//			0可用；1 冻结；2已出库 3 报废
			tmp.setBarcodeStatus("0");
			tmp.setActiveFlag("1");
			List<ProStorageSn> list = proStorageSnMapper.queryByAny(tmp);
			if(list != null && !list.isEmpty()){
				int modiAmount = proStorageSn.getModiAmount() != null ? proStorageSn.getModiAmount().intValue() : 0;
				if(modiAmount > list.size()){
					resp.setCode(Constant.FAIL);
					resp.setMsg("该合同下可用条码小于" + modiAmount + "个！");
					return resp;
				}
				List<Integer> ids = new ArrayList<Integer>();
				for(int i = 0; i < modiAmount; i++){
					ids.add(list.get(i).getStorageSnId());
				}
				
				ProStorageSn upOb = new ProStorageSn();
				upOb.setContractNo(proStorageSn.getContractNo());
				upOb.setProStorageSnIdList(ids);
				Integer upAmount = proStorageSnMapper.updateBySelectIds(upOb);
				if(modiAmount > upAmount){
					throw new RuntimeException("该合同内本次待修改条码状态发生改变，请再次尝试！");
				}
				
				//创建合同修改记录
				Date now = new Date();
				ProContractChange proContractChange = null;
				
				for(int i = 0; i < modiAmount; i++){
					proContractChange = new ProContractChange();
					proContractChange.setBarcode(list.get(i).getBarcode());
					proContractChange.setAmount(list.get(i).getAmount());
					proContractChange.setUnit(list.get(i).getUnit());
					proContractChange.setContractNoOld(proStorageSn.getContractNoOld());
					proContractChange.setContractNoNew(proStorageSn.getContractNo());
					proContractChange.setModel(list.get(i).getModel());
					proContractChange.setModelDesc(list.get(i).getModelDesc());
					proContractChange.setModelType(list.get(i).getModelType());
					proContractChange.setWlCode(list.get(i).getWlCode());
					//controller中的登陆人暂存在LastModifiedBy
					proContractChange.setCreateBy(proStorageSn.getLastModifiedBy());
					proContractChange.setGmtCreate(now);
					proContractChange.setActiveFlag("1");
					proContractChangeMapper.create(proContractChange);
				}
			}
			return resp;
		
		}
}
